const query = require("../db/mysql");
const {success,error}=require('../model/model')

class Cart {
    ///购物车列表
    getCartList = async (ctx) => {
        const { user_id } = ctx.query;
        const sql = `select * from carts where user_id="${user_id}" `
        const data = await query(sql)
        // ctx.body=data
        const allP = data.map((item) => {
            return new Promise(async (resolve, reject) => {
                try {
                    const res = await query(`select * from shops where id="${item.shop_id}" `)
                    resolve(res)
                } catch (err) {
                    reject(err)
                }
            })
        })
        const shops = await Promise.all(allP)
        const newData=data.forEach((item,index)=>{
            return {...shops[index][0],...item}
        })
        // ctx.body=success(newData)
        ctx.body=success({
            data,
            shops
        })
    }
    ///添加列表数据
    addCartList=async(ctx)=>{
        const {user_id,shop_id}=ctx.request.body
        const isHaveSql=`select * from carts where user_id="${user_id}" and  shop_id="${shop_id}" `
        const isHave=await query(isHaveSql)
        let data;
        if(isHave.length){
            const sql=`update carts set user_id="${isHave[0].count+=1}" and id="${isHave[0].id}" `;
            data=await query(sql)
        }else{
            const sql=`insert into carts(user_id,shop_id,count) values("${user_id}","${shop_id}","${1}")  `;
            data=await query(sql)
        }
        if(data.affectedRows===1){
            ctx.body={
                code:1,
                data
            }
        }else{
            ctx.body={
                code:-1,
                message:'加入失败'
            }
        }
    }
    ///删除购物车列表数据
    delCartList=async(ctx)=>{
        const {id}=ctx.params
        const sql=`delete from carts where id="${id}" `;
        const data=await query(sql)
        if(data.affectedRows===1){
             ctx.body=success('删除成功')
        }else{
            ctx.body=error('删除失败')
        }
    }
}
module.exports = new Cart()